package com.passist.email;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * 消费者
 */
@Component
public class Consumer {

    @Autowired
    private JavaMailSender javaMailSender;


    @Value("${spring.mail.username}")
    private String hostEmail;

    /**
     * 幂等性
     * @param msg
     * @throws Exception
     */
    @JmsListener(destination = "${my_queue}")
    public void receive(String msg) throws Exception {
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        /** 1.解析json **/
        JSONObject parseObject = JSONObject.parseObject(msg);
        String userName = parseObject.getString("userName");
        String email = parseObject.getString("email");
        String content = parseObject.getString("content");
        sendSimpleMail(email, userName, content);
        System.out.println("采用点对点模式，消费者成功获取到生产者的消息,msg:" + msg);

    }

    public void sendSimpleMail(String eamil, String userName, String content) throws Exception {
        SimpleMailMessage message = new SimpleMailMessage();
        /** 邮件来自 自己发自己 **/
        message.setFrom(hostEmail);
        /** 发送给谁 **/
        message.setTo(eamil);
        /** 邮件标题 **/
        message.setSubject( userName + " -> 激活邮箱");
        /** 邮件内容 **/
        message.setText(content);
        /** 发送邮件 **/
        javaMailSender.send(message);
        System.out.println("邮件发送完成," + JSONObject.toJSONString(message));
    }

}